package org.example.completed.utils;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class Interceptor implements HandlerInterceptor {
    // 注入redis
    @Autowired
    StringRedisTemplate redisTemplate;

    // 处理请求之前执行
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
        // 取出请求头中Authorization的信息，就是token内容，接下来就是各种判断
        String requestToken = request.getHeader("Authorization");
        if (!StringUtils.isEmpty(requestToken)) {
            Claims claims = JwtUtil.checkToken(request.getHeader("Authorization"));
            if (claims != null) {
                String token = redisTemplate.opsForValue().get("operToken" + claims.get("operNo"));
                if (Boolean.TRUE.equals(redisTemplate.hasKey("operToken" + claims.get("operNo")))) {
                    if (requestToken.equals(token)) {
                        // token正确
                        return true;
                    } else {
                        // token错误，判为并发登录，挤下线
                        // 对应的修改响应头的状态，用于前端判断做出相应的策略
                        response.setStatus(411);
                        return false;
                    }
                } else {
                    // token不存在于redis中，已过期
                    response.setStatus(410);
                    return false;
                }
            }
            // 解析token中的用户信息claims为null
            response.setStatus(409);
            return false;
        }
        // requestToken为空
        response.setStatus(409);
        return false;
    }

    // 处理请求之后执行
    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("处理请求之后执行");
    }


}
